package com.stylefeng.guns.modular.system.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.common.bo.WebuserBo;
import com.stylefeng.guns.common.constant.enums.IsAdd;
import com.stylefeng.guns.common.exception.BizExceptionEnum;
import com.stylefeng.guns.common.persistence.dao.*;
import com.stylefeng.guns.common.persistence.model.Webuser;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.support.CipherMd5Util;
import com.stylefeng.guns.modular.system.service.IWebuserService;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * C端用户表 服务实现类
 * </p>
 *
 * @author stylefeng123
 * @since 2018-01-21
 **/

@Service
@Slf4j
public class WebuserServiceImpl extends ServiceImpl<WebuserMapper, Webuser> implements IWebuserService {

    @Autowired
    private WebuserMapper webuserMapper;


    @Autowired
    private DictMapper dictMapper;


    @Override
    public int updateAccountMoney(Integer userId, BigDecimal amount) {
        return webuserMapper.updateAccountMoney(userId, amount);
    }

    @Override
    public boolean registerUser(String mobileNo, String cipher) {
        return false;
    }


    /**
     * encodeCipher
     */
    public String encodeCipher(String cipher, String identityId) {
        return CipherMd5Util.cryptMd5(cipher, identityId);
    }


    @Override
    public boolean validLoginCipher(Webuser dbCipher, String cipher) {
        boolean valid = CipherMd5Util.verifyMd5(cipher, dbCipher.getLoginPassword(), dbCipher.getId().toString());
        // 如果验证失败,记录失败次数及失败时间
        if (!valid) {
            log.error("{}的密码校验失败,错粗次数+1", dbCipher.getId().toString());
            //TODO 记录登录缓存
        } else {
            //TODO 重置缓存
        }
        return valid;
    }



    private static final Integer regDict = 43;//注册



    @Transactional
    @Override
    public boolean forgetLoginCipherUser(String mobileNo, String cipher) {
        Webuser forgetCipher = new Webuser();
        forgetCipher.setTelno(mobileNo);
        Webuser modifyUser = webuserMapper.selectByTelNo(forgetCipher);
        if (modifyUser == null) {
            throw new GunsException(BizExceptionEnum.USER_NOT_REGISTER);
        }

        Webuser tmp = new Webuser();
        tmp.setId(modifyUser.getId());
        tmp.setLoginPassword(encodeCipher(cipher, modifyUser.getId().toString()));//设置登录密码
        int updateFlag = webuserMapper.updateByPrimaryKeySelective(tmp);

        return BooleanUtils.toBoolean(updateFlag);
    }

    /**
     * 修改登录密码
     */
    @Override
    public boolean modifyLoginCipher(WebuserBo webuserBo, String cipher, String newCipher) {

        if (!StringUtils.equals(encodeCipher(cipher, webuserBo.getId().toString()), webuserBo.getLoginPassword())) {
            throw new GunsException(BizExceptionEnum.ORIG_LOGIN_CIPHER_ERROR_2);//原登陆密码不正确
        }
        Webuser tmp = new Webuser();
        tmp.setId(webuserBo.getId());
        tmp.setLoginPassword(encodeCipher(newCipher, webuserBo.getId().toString()));
        int updateFlag = webuserMapper.updateByPrimaryKeySelective(tmp);
        return BooleanUtils.toBoolean(updateFlag);
    }

    /**
     * 修改支付密码
     */
    @Transactional
    @Override
    public boolean modifyPayCipher(String mobileNo, String cipher, String newCipher) {
        Webuser forgetCipher = new Webuser();
        forgetCipher.setTelno(mobileNo);
        Webuser modifyUser = webuserMapper.selectByTelNo(forgetCipher);
        if (modifyUser == null) {
            throw new GunsException(BizExceptionEnum.USER_NOT_REGISTER);
        }
        if (StringUtils.isBlank(modifyUser.getPayPassword())) {
            throw new GunsException(BizExceptionEnum.PAY_CIPHER_NOT_EXIST);
        }
        if (!StringUtils.equals(encodeCipher(cipher, modifyUser.getId().toString()), modifyUser.getPayPassword())) {
            throw new GunsException(BizExceptionEnum.PAY_CIPHER_ERROR);
        }
        return setPayCipher(modifyUser, newCipher);
    }

    /**
     * 设置支付密码
     */
    @Transactional
    @Override
    public boolean setPayCipher(Webuser modifyWebuser, String cipher) {
        Webuser tmp = new Webuser();
        tmp.setId(modifyWebuser.getId());
        tmp.setPayPassword(encodeCipher(cipher, modifyWebuser.getId().toString()));
        int updateFlag = webuserMapper.updateByPrimaryKeySelective(tmp);
        return BooleanUtils.toBoolean(updateFlag);
    }

    /**
     * 忘记支付密码
     */
    @Transactional
    @Override
    public boolean forgetPayCipher(String mobileNo, String cipher) {
        Webuser forgetCipher = new Webuser();
        forgetCipher.setTelno(mobileNo);
        Webuser modifyUser = webuserMapper.selectByTelNo(forgetCipher);
        if (modifyUser == null) {
            throw new GunsException(BizExceptionEnum.USER_NOT_REGISTER);
        }
        return setPayCipher(modifyUser, cipher);
    }

    @Transactional
    @Override
    public boolean addPayCipher(String mobileNo, String cipher) {
        Webuser forgetCipher = new Webuser();
        forgetCipher.setTelno(mobileNo);
        Webuser modifyUser = webuserMapper.selectByTelNo(forgetCipher);
        if (modifyUser == null) {
            throw new GunsException(BizExceptionEnum.USER_NOT_REGISTER);
        }
        if (StringUtils.isNotBlank(modifyUser.getPayPassword())) {
            throw new GunsException(BizExceptionEnum.PAY_CIPHER_EXIST);//支付密码已经存在
        }
        return setPayCipher(modifyUser, cipher);
    }

    @Override
    public void updateTradeRank() {

    }

    @Override
    public Webuser qryExistWebUserByTelno(String telno) {
        Webuser tmp = new Webuser();
        tmp.setTelno(telno);
        Webuser webuser = webuserMapper.selectByTelNo(tmp);
        if (webuser == null) {
            throw new GunsException(BizExceptionEnum.USER_NOT_REGISTER);
        }
        return webuser;
    }

    @Override
    public boolean validPayCipher(Webuser dbCipher, String cipher) {
        boolean valid = CipherMd5Util.verifyMd5(cipher, dbCipher.getPayPassword(), dbCipher.getId().toString());
        // 如果验证失败,记录失败次数及失败时间
        if (!valid) {
            log.error("{}的密码校验失败,错粗次数+1", dbCipher.getId().toString());
            //TODO 记录登录缓存
        } else {
            //TODO 重置缓存
        }
        return valid;
    }


    @Override
    public void updateMoney(Integer userId, IsAdd isAdd, BigDecimal amount) {
        if (isAdd.equals(IsAdd.NO)) {
            amount = amount.multiply(new BigDecimal(-1));//转换为负数
        }
        int result = updateAccountMoney(userId, amount);
        if (result != 1) {
            throw new GunsException(BizExceptionEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 每天用户增量  (自己注册 会员推荐 合资公司 代理商）
     * 精确到日期
     *
     * @param begindatetime 查询开始时间
     * @param enddatetime   查询结束时间
     */
    public List<Map<String, Object>> getReportByDay(@Param("begindatetime") String begindatetime, @Param("enddatetime") String enddatetime) {
        return webuserMapper.getReportByDay(begindatetime, enddatetime);
    }


    /**
     * 每天用户增量  (自己注册 会员推荐 合资公司 代理商）
     * 精确到月
     *
     * @param begindatetime 查询开始时间
     * @param enddatetime   查询结束时间
     */
    public List<Map<String, Object>> getReportByMonth(@Param("begindatetime") String begindatetime, @Param("enddatetime") String enddatetime) {
        return webuserMapper.getReportByMonth(begindatetime, enddatetime);
    }

    /**
     * 每天用户增量  (自己注册 会员推荐 合资公司 代理商）
     * 精确到年
     *
     * @param begindatetime 查询开始时间
     * @param enddatetime   查询结束时间
     */
    public List<Map<String, Object>> getReportByYear(@Param("begindatetime") String begindatetime, @Param("enddatetime") String enddatetime) {
        return webuserMapper.getReportByYear(begindatetime, enddatetime);
    }



    /**
     * 转人工处理提交
     *
     * @param webuser
     */
    public void updateMoney(Webuser webuser) {
        webuserMapper.updateMoney(webuser);
    }


    /**
     * 根据邀请码增加积分
     *
     * @param inviteCode
     */
    @Override
    public void increaseInviteCode(String inviteCode) {
        Webuser webuser = webuserMapper.getWebuserByInviteCode(inviteCode);
        if (webuser != null) {
            Integer number = webuser.getIntegralNumber();
            number = number + 100;
            Integer id = webuser.getId();
            webuserMapper.updateInviteCode(id, number);
        }
    }

}
